package com.hobee.basic.config.rabbit;

import com.hobee.basic.config.rabbit.consumer.ConsumerHandler;
import com.hobee.basic.config.rabbit.consumer.NicelooConsumerHandler;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author junjie.li
 * @date 2020/7/21 14:58
 */
@Component
public class MQAcknowledgeReceiver implements ChannelAwareMessageListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(MQCallbackConfig.class);

    @Autowired
    private ConsumerHandler consumerHandler;



    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            MessageProperties messageProperties = message.getMessageProperties();
            String consumerQueue = messageProperties.getConsumerQueue();
            switch (consumerQueue) {
                case MQConfig.QUEUE_NICELOO_BOOT:
                    consumerHandler.consumer(NicelooConsumerHandler.class, new String(message.getBody()), messageProperties.getMessageId());
                    break;
                default:
            }
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            // 为true会重新放回队列
            channel.basicReject(deliveryTag, false);
            LOGGER.error(e.getMessage(), e);
        }
    }

}
